import { createStore } from 'vuex'
import axios from 'axios'

export default createStore({
  // 数据
  state: {
    cart: []
  },
  // 计算属性
  getters: {
    amount(state) {
      return state.cart
        .filter(item => item.goods_state)
        .reduce((amt, item) => (amt += item.goods_count * item.goods_price), 0)
    },
    total(state) {
      return state.cart
        .filter(item => item.goods_state)
        .reduce((t, item) => (t += item.goods_count), 0)
    },
    isFull(state) {
      return state.cart.every(item => item.goods_state)
    }
  },
  // 方法
  mutations: {
    updateCart(state, arr) {
      state.cart = arr
    },
    updateGoodsState(state, obj) {
      const result = state.cart.find(item => item.id === obj.id)
      result && (result.goods_state = obj.value)
    },
    updateGoodsCount(state, obj) {
      const result = state.cart.find(item => item.id === obj.id)
      result && (result.goods_count = obj.count)
    },
    updateAllState(state, boo) {
      state.cart.forEach(item => (item.goods_state = boo))
    }
  },
  // 异步操作
  actions: {
    async initCartList(ctx) {
      const { data: res } = await axios.get('https://www.escook.cn/api/cart')
      ctx.commit('updateCart', res.list)
    }
  }
})
